<template>
  <div class="container">
    <uv-navbar :placeholder="true">
      <template v-slot:left>
        <view class="uv-nav-slot flex alignCenter">
          <uv-icon name="arrow-left" size="19" @click="proxy.$utils.back()"></uv-icon>
          <uv-avatar :src="info.logo" size="28"></uv-avatar>
          <view class="nickName fz16 bold">{{info.nickName}}</view>
          <view class="matching">
            匹配度 {{info.matchingDegree}}%
          </view>
        </view>
      </template>

      <template v-slot:right>
        <view class="uv-nav-slot flex alignCenter" @click="toFollow">
          <view class="isFollow fz12">{{isFollow ? '取消关注' : '关注'}}</view>
        </view>
        <uv-icon name="more-dot-fill" size="19"></uv-icon>
      </template>
    </uv-navbar>

    <view class="top" v-if="false">
      <view class="label fz14">{{info.sex==1?'他':'她'}}希望的你</view>
      <view class="tags flex alignCenter" v-if="info.hisTags">
        <view class="tag fz12" v-for="(tag, index) in info.hisTags.split(',')" :key="index">{{tag}}</view>
      </view>

      <view class="label fz14">{{info.sex==1?'他':'她'}}是这样的</view>
      <view class="tags flex alignCenter" v-if="info.oneselfTags">
        <view class="tag pink fz12" v-for="(tag, index) in info.oneselfTags.split(',')" :key="index">{{tag}}</view>
      </view>
    </view>

    <scroll-view id="chatWrap" :scroll-top="scrollTop" @scrolltoupper="scrolltoupper" :scroll-y="true" :style="{height:chatHeight+'px'}">
      <view class="chat-list" id="chatList">
        <view class="chat-item" v-for="(item, index) in historyMsgs" :key="index">
          <view class="left flex" :class="{alignCenter:item.type=='audio'}" v-if="item.to!=info.userId">
            <uv-avatar :src="info.logo"></uv-avatar>
            <view class="con">
              <view class="text fz16" v-if="item.type=='text'">{{item.body}}</view>
              <view class="geo fz16" v-else-if="item.type=='geo'" @click="toLocation(item.attach)">
                <view class="title">{{item.attach.title}}</view>
                <view class="address">
                  <image :src="mapImageUrl(item.attach.lat, item.attach.lng)" mode="widthFix" />
                </view>
              </view>
              <view class="geo" v-else-if="item.type=='image'">
                <view class="address" @click="proxy.$auth.previewImage([item.attach.url],0)">
                  <image :src="item.attach.url" mode="widthFix" />
                </view>
              </view>
              <view v-else-if="item.type=='audio'">
                <customAudio :audioSrc="item.attach.url"></customAudio>
              </view>
              <view v-else-if="item.type=='custom'" class="flex alignCenter customMsg">
                <view class="image">
                  <image :src="item.attach.url" mode="widthFix" />
                </view>
                <view>{{item.attach.name}} x{{item.attach.num}}</view>
              </view>
            </view>
          </view>
          <view class="right flex justifyEnd" :class="{alignCenter:item.type=='audio'}" v-else>
            <view class="con">
              <view class="text fz16" v-if="item.type=='text'">{{item.body}}</view>
              <view class="geo fz16" v-else-if="item.type=='geo'" @click="toLocation(item.attach)">
                <view class="title">{{item.attach.title}}</view>
                <view class="address">
                  <image :src="mapImageUrl(item.attach.lat, item.attach.lng)" mode="widthFix" />
                </view>
              </view>
              <view class="geo" v-else-if="item.type=='image'">
                <view class="address" @click="proxy.$auth.previewImage([item.attach.url],0)">
                  <image :src="item.attach.url" mode="widthFix" />
                </view>
              </view>
              <view v-else-if="item.type=='audio'">
                <customAudio :audioSrc="item.attach.url"></customAudio>
              </view>
              <view v-else-if="item.type=='custom'" class="flex alignCenter customMsg">
                <view class="image">
                  <image :src="item.attach.url" mode="widthFix" />
                </view>
                <view>{{item.attach.name}} x{{item.attach.num}}</view>
              </view>
            </view>
            <uv-avatar :src="userInfo.logo"></uv-avatar>
          </view>
        </view>
      </view>
    </scroll-view>

    <chatAction id="chatActionDiv" @sendAudioMsg="sendAudioMsg" @getChatActionHeight="setCss" @sendMessage="sendMsg" @sendImageMsg="sendImageMsg"></chatAction>
  </div>
</template>

<script setup lang="ts">
import customAudio from "@/components/uv/customAudio.vue";
import chatAction from "@/packagePages/chatIm/components/chatAction.vue";
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const { proxy } = getCurrentInstance();
const instance = getCurrentInstance();

//im
import nimStore from "@/stores/nim";
const nim = nimStore();

let userId;
let info = ref({}); //用户信息
let isFollow = ref(false); //是否关注
let scrollTop = ref(0); //滚动条位置
let chatHeight = ref(0); //聊天区域高度
let historyMsgs = ref([]); //历史消息
let chatEndTime = Date.now(); //聊天会话结束时间
let loading = ref(false);

let userInfo = computed(() => {
  let slParams = uni.getStorageSync("slParams");
  return slParams.userInfo;
});

onLoad((e) => {
  userId = e.userId;
});

onShow(async () => {
  await getUserInfo();
  setCss();
  getHistoryMsgs();
});

let getUserInfo = async () => {
  //用户信息
  info.value = await counter.getUserInfo(userId);
  console.log("用户信息", info.value);

  //关注状态
  isFollow.value = await proxy.$apis.attentionToIt({ friendId: userId });
  console.log("关注状态", isFollow.value);
};

function setCss(hei?) {
  let footerHeight;
  nextTick(async () => {
    if (hei) {
      footerHeight = hei;
    } else {
      footerHeight = await viewInfo("#chatActionDiv", "height");
    }
    let top = await viewInfo("#chatWrap", "top");
    const systemInfo = uni.getSystemInfoSync();
    chatHeight.value = systemInfo.windowHeight - footerHeight - Number(top);
    scrollToBottom();
  });
}

//滚动到页面底部
function scrollToBottom() {
  nextTick(async () => {
    let chatWrapHeight = await viewInfo("#chatWrap", "height");
    let chatListHeight = await viewInfo("#chatList", "height");
    if (chatListHeight > chatWrapHeight)
      scrollTop.value = Number(chatListHeight) - Number(chatWrapHeight);
  });
}

async function getHistoryMsgs(e?) {
  let arr = await nim.getHistoryMsgs(info.value.userId, chatEndTime);
  if (e && e == 1) {
    let list = proxy.$utils.deepcopy(historyMsgs.value);
    list = proxy.$utils.filterArr(list, arr, "idServer");
    historyMsgs.value = list.sort(proxy.$utils.compare("time"));
  } else {
    historyMsgs.value = arr;
    if (!arr.length) await sendMsg("你好👋，交个朋友吧～");
    if (arr.length) {
      await nim.sendMsgReceipt(arr[arr.length - 1]);
      await nim.resetSessionUnreadCount(arr[arr.length - 1].sessionId);
    }
    scrollToBottom();
  }
}

async function toFollow() {
  try {
    loading.value = true;
    //已关注
    if (isFollow.value) {
      await proxy.$apis.userUnFocus({ friendId: userId });
      proxy.$utils.showToast("已取消关注");
    } else {
      await proxy.$apis.contacts({ friendId: userId });
      proxy.$utils.showToast("已成功关注");
    }
    getUserInfo();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

//滚动到顶部
function scrolltoupper() {
  chatEndTime = historyMsgs.value[0].time;
  getHistoryMsgs(1);
}

//发送文本消息
async function sendMsg(text) {
  await nim.sendMsg(info.value.userId, text);
}

function toLocation(params) {
  proxy.$auth.openLocation({
    latitude: params.lat,
    longitude: params.lng,
    name: params.title,
  });
}

//发送图片
async function sendImageMsg(text) {
  await nim.sendImageMsg(info.value.userId, text);
}

//发送语音消息
async function sendAudioMsg(text) {
  await nim.sendAudioMsg(info.value.userId, text);
}

//发送地址
async function sendAddressMsg(text) {
  await nim.sendGeoLocationMsg(info.value.userId, text);
}

function mapImageUrl(lat, lng) {
  return proxy.$atlas.staticmapImage(lat, lng);
}

//获取页面元素信息
function viewInfo(id, type) {
  return new Promise((resolve, reject) => {
    uni
      .createSelectorQuery()
      .in(instance)
      .select(id)
      .boundingClientRect((data) => {
        if (data) {
          resolve(data[type]);
        } else {
          resolve(0);
        }
      })
      .exec();
  });
}

watch(
  () => nim.msgUpdate,
  (newValue, oldValue) => {
    if (newValue) {
      if (newValue.to == userInfo.value.userId) {
        if (newValue.type == "custom")
          proxy.$utils.showToast(
            `收到${newValue.attach.name} x${newValue.attach.num}`
          );
        historyMsgs.value.push(newValue);
        scrollToBottom();
      }
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => nim.updateSession,
  (newValue, oldValue) => {
    if (
      newValue &&
      !proxy.$utils.isEmptyObject(newValue) &&
      newValue.lastMsg.hasOwnProperty("idServer")
    ) {
      if (newValue.lastMsg.from == userInfo.value.userId) {
        let arr = proxy.$utils.deepcopy(historyMsgs.value);
        historyMsgs.value = proxy.$utils.filterArr(
          arr,
          [newValue.lastMsg],
          "idServer"
        );
        scrollToBottom();
      }
    }
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.container {
  .nickName {
    color: #333333;
    padding: 0 10px;
  }
  .matching {
    background: linear-gradient(to right, #ffa0d2, #4439ff);
    border-radius: 11px;
    color: #fff;
    font-size: 12px;
    padding: 3px 6px;
  }
  .isFollow {
    background: #9e06ff;
    border-radius: 15px;
    line-height: 21px;
    color: white;
    padding: 3px 12px;
    margin-right: 12px;
  }
  .top {
    padding: 10px 27px;
    box-shadow: 0 2px 4px 0px rgba(0, 0, 0, 0.05);
    border-radius: 0 0 15px 15px;
    .label {
      color: #999999;
    }
    .tags {
      color: #9e06ff;
      flex-wrap: wrap;
      margin-top: 5px;
      .tag {
        padding: 4px 6px;
        margin-right: 10px;
        margin-bottom: 10px;
        border: 1px solid #9e06ff;
        border-radius: 12px;
      }
      .pink {
        border-color: #f667a7 !important;
        color: #f667a7 !important;
      }
    }
  }
  .chat-list {
    padding: 15px;
    .chat-item {
      margin-bottom: 10px;
      .left {
        .con {
          margin-left: 10px;
        }
        .text {
          padding: 9px 10px 9px 10px;
          border-radius: 20px 20px 20px 0;
          background: #ededed;
          color: #333333;
        }
      }
      .right {
        .con {
          margin-right: 10px;
        }
        .text {
          color: white;
          padding: 9px 10px 9px 10px;
          border-radius: 20px 20px 0px 20px;
          background: #9e06ff;
        }
      }
      .geo {
        width: 150px;
        background-color: white;
        border-radius: 5px;
        .title {
          padding: 10px;
          font-size: 14px;
        }
        .address {
          image {
            display: block;
          }
        }
      }
      .customMsg {
        background-color: white;
        padding: 3px 10px;
        border-radius: 5px;
        font-size: 14px;
        .image {
          width: 30px;
          margin-right: 2px;
        }
      }
    }
  }
}
</style>
